<template>
  <el-form ref="userRef" :model="form" :rules="rules" label-width="90px" show-password>
    <el-form-item label="Excel密码" prop="excelPassword">
      <el-input
        v-model="form.excelPassword"
        placeholder="请输入Excel密码（如未设置密码，则不用填）"
        type="password"
        show-password
      />
    </el-form-item>
    <el-button type="primary" @click="submit">保存</el-button>
    <el-button type="danger" @click="close">关闭</el-button>
  </el-form>
</template>

<script setup>
  import { ref, watch, getCurrentInstance } from 'vue';
  import { updateUserExcel } from '@/api/system/user';

  const { proxy } = getCurrentInstance();
  const form = ref({});

  // props是传递的数据
  const props = defineProps({
    user: {
      type: Object,
    },
  });

  const rules = ref({
    excelPassword: [
      { required: true, message: 'Excel密码不能为空', trigger: 'blur' },
      { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' },
    ],
  });

  /** 提交按钮 */
  function submit() {
    proxy.$refs.userRef.validate((valid) => {
      if (valid) {
        updateUserExcel(form.value).then(() => {
          proxy.$modal.msgSuccess('修改成功');
          props.user.excelPassword = form.value.excelPassword;
        });
      }
    });
  }

  /** 关闭按钮 */
  function close() {
    proxy.$tab.closePage();
  }

  // 回显当前登录用户信息
  watch(
    () => props.user,
    (user) => {
      if (user) {
        form.value = { excelPassword: user.excelPassword };
      }
    },
    { immediate: true },
  );
</script>
